const fs = require('fs');

const addMapping = (router, mapping) => {
  for (let url in mapping) {
    let params = url.split(' ');
    let method = params[0].toLowerCase();
    let path = params[1];
    if(['get','post','put','delete','patch'].includes(method)){
      router[method](path, mapping[url]);
    }else{
      console.error('未知请求！');
      continue;
    }
  }
}

const addControllers = (router, dir) => {
  dir = __dirname + dir;
  const files = fs.readdirSync(dir)
  const jsFiles = files.filter(f => f.endsWith('.js'));
  for (let f of jsFiles) {
    console.log(`处理控制器: ${f}...`)
    let mapping = require(dir + f);
    addMapping(router, mapping)
  }
}

module.exports = function(dir) {
  let router = require('koa-router')();
  dir = dir || '/controllers/';
  addControllers(router, dir);
  return router.routes();
}